#include "general.h"
#include "sql_commands.h"

#include <buolabase_basicio.h>
#include <cfile.h>

void CDataServer::OpenDatabase()
{
	CURL lURL(CURL::GetHome()+".buola"+"bigbrother"+"metadata.db");
	PFile lFile=CFile::Get(lURL);
	bool lExisted=lFile->Exists();
	
	mDB=mDBEngine->GetDatabase();
	mDB->SetFileName(lURL);
	mDB->Connect();

	mDB->RunSimpleQuery(sPragmas);

	if(!lExisted)
	{
		mDB->RunSimpleQuery(sCreateDataTables);
		mDB->RunSimpleQuery(sInsertDefaultData);
	}
}

void CDataServer::CloseDatabase()
{
	delete mDB;
}

void CDataServer::PrepareQueries()
{
	mQueries.mInsertMetadata=mDB->GetQuery();
	mQueries.mInsertMetadata->Prepare(sInsertMetadata);
	mQueries.mInsertTag=mDB->GetQuery();
	mQueries.mInsertTag->Prepare(sInsertTag);
	mQueries.mInsertFolder=mDB->GetQuery();
	mQueries.mInsertFolder->Prepare(sInsertFolder);
	mQueries.mInsertObject=mDB->GetQuery();
	mQueries.mInsertObject->Prepare(sInsertObject);
	mQueries.mInsertObjectTag=mDB->GetQuery();
	mQueries.mInsertObjectTag->Prepare(sInsertObjectTag);
	mQueries.mInsertObjectMetadata=mDB->GetQuery();
	mQueries.mInsertObjectMetadata->Prepare(sInsertObjectMetadata);
	mQueries.mGetFolderID=mDB->GetQuery();
	mQueries.mGetFolderID->Prepare(sGetFolderID);
	mQueries.mGetObjectID=mDB->GetQuery();
	mQueries.mGetObjectID->Prepare(sGetObjectID);
	mQueries.mGetObject=mDB->GetQuery();
	mQueries.mGetObject->Prepare(sGetObject);
	mQueries.mGetMetadata=mDB->GetQuery();
	mQueries.mGetMetadata->Prepare(sGetMetadata);
	mQueries.mGetObjectMetadata=mDB->GetQuery();
	mQueries.mGetObjectMetadata->Prepare(sGetObjectMetadata);
}
